<?php

namespace App\Http\Controllers\Wechat;

use App\Models\User;
use Validator;
use App\Http\Controllers\Controller;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;
use App\Libraries\Weixin;
use GuzzleHttp\Client;

class AuthController extends Controller {

    public function getRegister(Application $wechat) {
        if (empty(session('wechat_userinfo'))) {
            session(['target_url' => 'register']);
            return $wechat->oauth->scopes(['snsapi_userinfo'])
                            ->redirect();
        }
        $userinfo = session('wechat_userinfo');
        return view('wechat.user.register');
    }

    public function postRegister(Request $request) {
        $smsCode = $request->input('code');
        if (empty($smsCode)) {
            return ['status' => 0, 'msg' => '请填写验证码'];
        } elseif (session('sms_code') != $smsCode) {
            return ['status' => 0, 'msg' => '验证码错误!'];
        }
        $userinfo = session('wechat_userinfo');
        $messages = [
            'name.required' => '请填写姓名',
            'name.max' => '姓名格式有误',
            'id_card.required' => '请填写身份证号码',
            'id_card.identitycards' => '身份证号码格式有误',
            'id_card.unique' => '身份证号码已被注册',
            'telphone.required' => '请填写手机号码',
            'telphone.telphone' => '手机号码格式有误',
            'telphone.unique' => '手机号码已被注册'
        ];
        $validator = Validator::make($request->all(), [
                    'name' => 'required|max:5',
                    'id_card' => 'required|identitycards|unique:users',
                    'telphone' => 'required|telphone|unique:users',
                        ], $messages);

        if ($validator->fails()) {
            $errorMsg = $validator->errors()->all();
            //如果验证未通过，返回第一条错误信息
            return ['status' => 0, 'msg' => $errorMsg[0]];
        }
        $checkIdCard = $this->checkIdCard($request->input('id_card'), $request->input('name'));
        if (!$checkIdCard) {
            return ['status' => 0, 'msg' => '身份证与姓名不匹配!'];
        }
//        if($userinfo['headimgurl']){
//            $avatar = file_get_contents($userinfo['headimgurl']);
//            file_put_contents(public_path('avatar').'/'. md5_file($userinfo['headimgurl']), $avatar);
//        }
        User::create([
            'name' => $request->input('name'),
            'id_card' => $request->input('id_card'),
            'telphone' => $request->input('telphone'),
            'sex' => $userinfo['sex'],
            'openid' => $userinfo['openid'],
            'status' => 1
        ]);
        session(['sms_code' => null]);
        return ['stauts' => 1, 'msg' => '注册成功!'];
    }

    public function sendSmsCode(Request $request) {
        $messages = [
            'telphone.required' => '请填写手机号码',
            'telphone.telphone' => '手机号码格式有误',
            'telphone.unique' => '手机号码已被注册'
        ];
        $validator = Validator::make($request->all(), [
                    'telphone' => 'required|telphone|unique:users',
                        ], $messages);
        if ($validator->fails()) {
            $errorMsg = $validator->errors()->all();
            //如果验证未通过，返回第一条错误信息
            return ['status' => 0, 'msg' => $errorMsg[0]];
        }
        $xmlstring = sendSmsCode($request->input('telphone'));
        $xml = simplexml_load_string($xmlstring);                     //将xml字符串转化为对象
        $res = json_decode(json_encode($xml), true);
        if ($res['returnstatus'] == 'Success') {
            return ['stauts' => 1, 'msg' => '短信发送成功!'];
        } else {
            return ['stauts' => 0, 'msg' => $res['message']];
        }
    }

    public function regSuccess(Application $wechat) {
        $js = $wechat->js;
        return view('wechat.user.regSuccess', ['js' => $js]);
    }

    public function checkIdCard($cardNo, $realName) {
        $key = '3e064fa4533219a184b6db704816435a';
        $client = new Client(['base_uri' => 'http://v.apistore.cn/api/a1']);
        $res = $client->request('POST', '', [
            'form_params' => [
                'key' => $key,
                'cardNo' => $cardNo,
                'realName' => $realName,
                'information' => 0
            ]
        ]);
        $checkArr = json_decode((string) $res->getBody(), true);
        if (isset($checkArr['error_code']) && $checkArr['error_code'] === 0) {
            return true;
        }
        return false;
    }

}
